package com.gxa.shop.servlet.category;

import com.alibaba.fastjson.JSON;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.service.category.CategoryService;
import com.gxa.shop.service.category.impl.CategoryServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * com.gxa.shop.bean.servlet.category
 * User: zjy
 * Date: 2024/12/17 14:30
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
@WebServlet(name = "CategoryDeleteByIdServlet",value = "/category/deleteById")
public class CategoryDeleteByIdServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String id = request.getParameter("categoryId");
        R r;

        try {
            if (id == null || id.trim().isEmpty()) {
                throw new IllegalArgumentException("ID编号不能为空");
            }
            Integer categoryId = Integer.parseInt(id.trim());
            CategoryService categoryService = new CategoryServiceImpl();
            boolean delete = categoryService.deleteById(categoryId);
            r = delete ? R.ok() : R.error("删除失败");
        } catch (NumberFormatException e) {
            r = R.error("ID编号不正确");
        } catch (IllegalArgumentException e) {
            r = R.error(e.getMessage());
        }

        PrintWriter writer = response.getWriter();
        String result = JSON.toJSONString(r);
        System.out.println("DeleteByIdServlet:" + result);
        writer.write(result);
        writer.flush();
        writer.close();
    }
}